﻿using System;
using System.Data.SqlClient;
using System.Configuration;

namespace Wild2.Models.TimeOnSite
{
    public class TimeOnSite
    {
        public static void UpdateLastDateOnSite(Int32 userId)
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnect"].ConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand("UPDATE Users SET [LastOnlineDate] = GETDATE() WHERE (ID = @UID)", conn))
                {
                    cmd.Parameters.Add("@UID", System.Data.SqlDbType.Int).Value = userId;
                    cmd.Connection.Open();
                    cmd.ExecuteNonQuery();
                    cmd.Connection.Close();
                }
            }
        }

        public static void UpdateTimeOnSite(Int32 userId, TimeSpan ts)
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnect"].ConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand("UPDATE Users SET [TimeOnSite] = [TimeOnSite] + @TS WHERE (ID = @UID)", conn))
                {
                    cmd.Parameters.Add("@UID", System.Data.SqlDbType.Int).Value = userId;
                    cmd.Parameters.Add("@TS", System.Data.SqlDbType.BigInt).Value = Convert.ToInt64(ts.TotalSeconds);
                    cmd.Connection.Open();
                    cmd.ExecuteNonQuery();
                    cmd.Connection.Close();
                }
            }
        }

        public static TimeSpan GetTimeOnSite(Int32 userId)
        {
            TimeSpan ts = new TimeSpan();
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnect"].ConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand("SELECT [TimeOnSite] FROM [Users] WHERE (ID = @UID)", conn))
                {
                    cmd.Parameters.Add("@UID", System.Data.SqlDbType.Int).Value = userId;
                    cmd.Connection.Open();
                    ts = TimeSpan.FromSeconds(Convert.ToInt64(cmd.ExecuteScalar()));
                    cmd.Connection.Close();
                }
            }
            return ts;
        }
    }
}